<template>
  <div class="map-container">
    <div id="map" ref="mapRef"></div>
    <div v-if="loading" class="loading">正在加载路径数据 road.json ...</div>
    <div v-if="error" class="error">路径数据加载失败，请检查 public/road.json 是否存在且格式正确！</div>
    <div v-if="noData" class="nodata">未检测到有效路径数据！</div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import Map from 'ol/Map'
import View from 'ol/View'
import TileLayer from 'ol/layer/Tile'
import XYZ from 'ol/source/XYZ'
import VectorLayer from 'ol/layer/Vector'
import VectorSource from 'ol/source/Vector'
import { fromLonLat } from 'ol/proj'
import { PathAnimation } from '../utils/pathAnimation'

const mapRef = ref<HTMLElement | null>(null)
let map: Map | null = null
let pathAnimation: PathAnimation | null = null

const vectorSource = new VectorSource()
const vectorLayer = new VectorLayer({ source: vectorSource })

// 状态
const loading = ref(true)
const error = ref(false)
const noData = ref(false)

async function loadRoadJson() {
  loading.value = true
  error.value = false
  noData.value = false
  
  try {
    const res = await fetch('/road.json')
    const geojson = await res.json()
    
    if (geojson.features && geojson.features.length > 0) {
      // 居中并缩放到路径范围
      if (map) {
        const allCoords = geojson.features.flatMap((f: any) => f.geometry.coordinates)
          .map((c: number[]) => fromLonLat(c))
        
        let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity
        
        allCoords.forEach((coord: number[]) => {
          const [x, y] = coord
          minX = Math.min(minX, x)
          minY = Math.min(minY, y)
          maxX = Math.max(maxX, x)
          maxY = Math.max(maxY, y)
        })
        
        map.getView().fit([minX, minY, maxX, maxY], {
          padding: [40, 40, 40, 40],
          duration: 800
        })
      }
      
      // 开始动画
      if (pathAnimation) {
        pathAnimation.start(geojson, false) // 设置为 true 则会在完成后清除路径
      }
    } else {
      noData.value = true
    }
    
    loading.value = false
  } catch (e) {
    error.value = true
    loading.value = false
    console.error('加载road.json失败', e)
  }
}

onMounted(() => {
  if (!mapRef.value) return
  
  map = new Map({
    target: mapRef.value,
    layers: [
      new TileLayer({
        source: new XYZ({
          url: 'https://basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png'
        })
      }),
      vectorLayer
    ],
    view: new View({
      center: fromLonLat([114.1, 24.2]),
      zoom: 8
    })
  })
  
  // 初始化动画实例
  pathAnimation = new PathAnimation(vectorSource, {
    animationSpeed: 50 // 可以自定义动画速度
  })
  
  loadRoadJson()
})

onUnmounted(() => {
  if (pathAnimation) {
    pathAnimation.destroy()
  }
  if (map) {
    map.setTarget(undefined)
  }
})
</script>

<style scoped>
.map-container {
  width: 100vw;
  height: 100vh;
  background: #111;
  position: relative;
}

#map {
  width: 100%;
  height: 100%;
}

.loading, .error, .nodata {
  position: absolute;
  left: 50%;
  top: 30px;
  transform: translateX(-50%);
  background: rgba(0,0,0,0.7);
  color: #00eaff;
  padding: 8px 24px;
  border-radius: 8px;
  font-size: 18px;
  z-index: 10;
}

.error { color: #ff4d4f; }
.nodata { color: #ffd700; }
</style>

<script lang="ts">
export default {
  name: 'Map'
}
</script> 